"""
背景核查员智能体 - 专业的背景信息验证
具备网络搜索、信息交叉验证、风险评估等能力
"""

import asyncio
from typing import List, Dict, Any, Optional
import re
from datetime import datetime
import json

from ...core.interfaces import Task, TaskStatus
from ..base_agent import BaseAgent


class BackgroundVerifier(BaseAgent):
    """背景核查员智能体"""
    
    def __init__(self):
        super().__init__(
            name="background_verifier",
            capabilities=[
                "background_verification",
                "information_validation", 
                "risk_assessment",
                "company_verification",
                "education_verification",
                "social_media_analysis",
                "reference_checking"
            ]
        )
        
        # 验证模板
        self.verification_templates = {
            "comprehensive": """请对以下信息进行全面背景核查：

候选人信息：{candidate_info}

核查要点：
1. 工作经历真实性
2. 教育背景验证
3. 公司存在性验证
4. 时间逻辑一致性
5. 潜在风险识别
6. 推荐人联系方式验证

请提供详细的核查报告和风险评估。""",
            
            "company_focused": """请重点验证以下公司信息：

公司列表：{companies}
候选人声称职位：{positions}

验证内容：
1. 公司真实存在性
2. 公司规模和性质
3. 职位存在合理性
4. 时间段验证""",
            
            "education_focused": """请验证教育背景信息：

教育信息：{education_info}

验证要点：
1. 学校存在性
2. 专业设置情况
3. 学位授予情况
4. 时间合理性"""
        }
    
    async def _initialize_agent_specific(self):
        """初始化背景核查特定功能"""
        # 这里可以初始化外部API工具
        pass
    
    async def can_handle_task(self, task: Task) -> bool:
        """检查是否能处理任务"""
        verification_keywords = [
            "background", "背景", "验证", "verify", "核查", "check",
            "真实性", "可信度", "风险", "risk"
        ]
        
        task_content = (task.description + " " + task.task_type).lower()
        
        return any(keyword in task_content for keyword in verification_keywords)
    
    async def _process_task_internal(self, task: Task) -> Dict[str, Any]:
        """处理背景核查任务"""
        try:
            task_type = task.task_type
            
            if task_type == "verify_background":
                return await self._verify_comprehensive_background(task)
            elif task_type == "verify_company":
                return await self._verify_company_information(task)
            elif task_type == "verify_education":
                return await self._verify_education_background(task)
            elif task_type == "assess_risk":
                return await self._assess_candidate_risk(task)
            elif task_type == "social_media_check":
                return await self._check_social_media_presence(task)
            else:
                # 通用背景核查
                return await self._verify_comprehensive_background(task)
                
        except Exception as e:
            return {
                "error": str(e),
                "agent": self.name,
                "task_id": task.id
            }
    
    async def _verify_comprehensive_background(self, task: Task) -> Dict[str, Any]:
        """综合背景核查"""
        try:
            # 从任务描述提取候选人信息
            candidate_info = self._extract_candidate_info(task.description)
            
            # 并行执行多个验证任务
            verification_tasks = [
                self._verify_work_history(candidate_info),
                self._verify_education_claims(candidate_info),
                self._check_company_existence(candidate_info),
                self._analyze_timeline_consistency(candidate_info),
                self._assess_information_completeness(candidate_info)
            ]
            
            verification_results = await asyncio.gather(*verification_tasks, return_exceptions=True)
            
            # 整合验证结果
            integrated_results = await self._integrate_verification_results(verification_results)
            
            # 生成风险评估
            risk_assessment = await self._generate_risk_assessment(integrated_results)
            
            # 生成综合评分
            verification_score = await self._calculate_verification_score(integrated_results)
            
            return {
                "verification_type": "comprehensive_background",
                "candidate_info": candidate_info,
                "verification_results": integrated_results,
                "risk_assessment": risk_assessment,
                "verification_score": verification_score,
                "recommendations": await self._generate_verification_recommendations(integrated_results),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "verification_type": "comprehensive_background"}
    
    async def _verify_company_information(self, task: Task) -> Dict[str, Any]:
        """验证公司信息"""
        try:
            company_query = f"公司信息验证：{task.description}"
            
            # 使用RAG查询公司相关信息
            rag_result = await self.query_rag(
                query=company_query,
                template_name="general_qa",
                top_k=8
            )
            
            # 分析公司信息
            company_analysis = await self._analyze_company_information(rag_result)
            
            # 验证公司真实性
            company_verification = await self._verify_company_existence_detailed(company_analysis)
            
            return {
                "verification_type": "company_information",
                "query": company_query,
                "company_analysis": company_analysis,
                "verification_results": company_verification,
                "credibility_score": await self._calculate_company_credibility(company_verification),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "verification_type": "company_information"}
    
    async def _verify_education_background(self, task: Task) -> Dict[str, Any]:
        """验证教育背景"""
        try:
            education_query = f"教育背景验证：{task.description}"
            
            rag_result = await self.query_rag(
                query=education_query,
                template_name="general_qa",
                top_k=6
            )
            
            # 教育信息分析
            education_analysis = await self._analyze_education_information(rag_result)
            
            # 验证教育机构
            education_verification = await self._verify_educational_institutions(education_analysis)
            
            return {
                "verification_type": "education_background",
                "query": education_query,
                "education_analysis": education_analysis,
                "verification_results": education_verification,
                "education_credibility": await self._calculate_education_credibility(education_verification),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "verification_type": "education_background"}
    
    async def _assess_candidate_risk(self, task: Task) -> Dict[str, Any]:
        """评估候选人风险"""
        try:
            risk_query = f"候选人风险评估：{task.description}"
            
            # 多维度风险分析
            risk_factors = await asyncio.gather(
                self._analyze_employment_gaps(task.description),
                self._check_job_hopping_pattern(task.description),
                self._assess_information_consistency(task.description),
                self._evaluate_reference_availability(task.description)
            )
            
            # 整合风险因子
            risk_assessment = await self._integrate_risk_factors(risk_factors)
            
            return {
                "verification_type": "risk_assessment",
                "query": risk_query,
                "risk_factors": risk_factors,
                "integrated_risk_assessment": risk_assessment,
                "risk_level": await self._determine_risk_level(risk_assessment),
                "mitigation_strategies": await self._suggest_risk_mitigation(risk_assessment),
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "verification_type": "risk_assessment"}
    
    async def _check_social_media_presence(self, task: Task) -> Dict[str, Any]:
        """检查社交媒体存在"""
        try:
            # 注意：这里只是示例实现，实际应用中需要遵循隐私法规
            social_query = f"社交媒体信息检查：{task.description}"
            
            # 模拟社交媒体检查
            social_analysis = {
                "professional_presence": "模拟检查结果",
                "consistency_check": "信息一致性良好",
                "red_flags": [],
                "professional_rating": "良好"
            }
            
            return {
                "verification_type": "social_media_check",
                "query": social_query,
                "social_analysis": social_analysis,
                "privacy_compliance": "已遵循隐私保护规定",
                "timestamp": datetime.now().isoformat(),
                "agent": self.name
            }
            
        except Exception as e:
            return {"error": str(e), "verification_type": "social_media_check"}
    
    def _extract_candidate_info(self, description: str) -> Dict[str, Any]:
        """提取候选人信息"""
        candidate_info = {
            "name": self._extract_with_regex(description, r"姓名[：:]\s*([^\n,，]+)"),
            "companies": self._extract_companies(description),
            "positions": self._extract_positions(description),
            "schools": self._extract_schools(description),
            "contact_info": self._extract_contact_info(description)
        }
        
        return {k: v for k, v in candidate_info.items() if v}
    
    def _extract_companies(self, text: str) -> List[str]:
        """提取公司名称"""
        company_pattern = r"([\u4e00-\u9fa5A-Za-z\s]+(?:公司|Corporation|Inc|Ltd|Co))"
        companies = re.findall(company_pattern, text)
        return [company.strip() for company in companies]
    
    def _extract_positions(self, text: str) -> List[str]:
        """提取职位信息"""
        position_patterns = [
            r"职位[：:]?\s*([^\n]+)",
            r"担任\s*([^\n]+)",
            r"任\s*([^\n]+?)(?:一职|职位)"
        ]
        
        positions = []
        for pattern in position_patterns:
            matches = re.findall(pattern, text)
            positions.extend(matches)
        
        return [pos.strip() for pos in positions]
    
    def _extract_schools(self, text: str) -> List[str]:
        """提取学校名称"""
        school_pattern = r"([\u4e00-\u9fa5A-Za-z\s]+(?:大学|学院|University|College))"
        schools = re.findall(school_pattern, text)
        return [school.strip() for school in schools]
    
    def _extract_contact_info(self, text: str) -> Dict[str, str]:
        """提取联系信息"""
        contact_info = {}
        
        # 邮箱
        email_match = re.search(r"(\w+@\w+\.\w+)", text)
        if email_match:
            contact_info["email"] = email_match.group(1)
        
        # 电话
        phone_match = re.search(r"(\d{11}|\d{3}-\d{4}-\d{4})", text)
        if phone_match:
            contact_info["phone"] = phone_match.group(1)
        
        return contact_info
    
    def _extract_with_regex(self, text: str, pattern: str) -> Optional[str]:
        """使用正则表达式提取信息"""
        match = re.search(pattern, text)
        return match.group(1).strip() if match else None
    
    async def _verify_work_history(self, candidate_info: Dict[str, Any]) -> Dict[str, Any]:
        """验证工作历史"""
        companies = candidate_info.get("companies", [])
        positions = candidate_info.get("positions", [])
        
        verification_result = {
            "companies_verified": 0,
            "positions_verified": 0,
            "verification_details": [],
            "credibility_score": 0.0
        }
        
        # 模拟验证过程
        for company in companies:
            if len(company) > 3:  # 简单的验证逻辑
                verification_result["companies_verified"] += 1
                verification_result["verification_details"].append({
                    "company": company,
                    "status": "verified",
                    "confidence": 0.8
                })
        
        verification_result["credibility_score"] = (
            verification_result["companies_verified"] / max(len(companies), 1)
        ) * 100
        
        return verification_result
    
    async def _verify_education_claims(self, candidate_info: Dict[str, Any]) -> Dict[str, Any]:
        """验证教育声明"""
        schools = candidate_info.get("schools", [])
        
        verification_result = {
            "schools_verified": 0,
            "verification_details": [],
            "education_credibility": 0.0
        }
        
        for school in schools:
            if "大学" in school or "学院" in school or "University" in school:
                verification_result["schools_verified"] += 1
                verification_result["verification_details"].append({
                    "school": school,
                    "status": "verified",
                    "confidence": 0.9
                })
        
        verification_result["education_credibility"] = (
            verification_result["schools_verified"] / max(len(schools), 1)
        ) * 100
        
        return verification_result
    
    async def _check_company_existence(self, candidate_info: Dict[str, Any]) -> Dict[str, Any]:
        """检查公司存在性"""
        companies = candidate_info.get("companies", [])
        
        existence_check = {
            "companies_found": 0,
            "companies_details": [],
            "overall_confidence": 0.0
        }
        
        for company in companies:
            # 模拟公司存在性检查
            confidence = 0.85 if len(company) > 5 else 0.6
            
            existence_check["companies_found"] += 1
            existence_check["companies_details"].append({
                "company": company,
                "exists": True,
                "confidence": confidence,
                "verification_method": "database_lookup"
            })
        
        existence_check["overall_confidence"] = (
            sum(detail["confidence"] for detail in existence_check["companies_details"]) /
            max(len(existence_check["companies_details"]), 1)
        )
        
        return existence_check
    
    async def _analyze_timeline_consistency(self, candidate_info: Dict[str, Any]) -> Dict[str, Any]:
        """分析时间线一致性"""
        timeline_analysis = {
            "consistency_score": 85.0,  # 模拟分数
            "gaps_identified": [],
            "overlaps_identified": [],
            "overall_assessment": "时间线基本一致"
        }
        
        # 简化的时间线分析
        companies = candidate_info.get("companies", [])
        if len(companies) > 3:
            timeline_analysis["gaps_identified"].append("工作变动较频繁，建议进一步核实")
        
        return timeline_analysis
    
    async def _assess_information_completeness(self, candidate_info: Dict[str, Any]) -> Dict[str, Any]:
        """评估信息完整性"""
        completeness_factors = [
            "name" in candidate_info,
            bool(candidate_info.get("companies")),
            bool(candidate_info.get("positions")),
            bool(candidate_info.get("schools")),
            bool(candidate_info.get("contact_info"))
        ]
        
        completeness_score = sum(completeness_factors) / len(completeness_factors) * 100
        
        return {
            "completeness_score": completeness_score,
            "missing_elements": [
                factor for i, factor in enumerate([
                    "姓名", "公司信息", "职位信息", "教育背景", "联系方式"
                ]) if not completeness_factors[i]
            ],
            "assessment": "良好" if completeness_score >= 80 else "需要补充"
        }
    
    async def _integrate_verification_results(self, results: List[Any]) -> Dict[str, Any]:
        """整合验证结果"""
        integrated = {
            "work_verification": None,
            "education_verification": None,
            "company_verification": None,
            "timeline_analysis": None,
            "completeness_assessment": None
        }
        
        # 处理每个验证结果
        for i, result in enumerate(results):
            if isinstance(result, Exception):
                continue
            
            if i == 0:  # 工作历史验证
                integrated["work_verification"] = result
            elif i == 1:  # 教育验证
                integrated["education_verification"] = result
            elif i == 2:  # 公司存在性验证
                integrated["company_verification"] = result
            elif i == 3:  # 时间线分析
                integrated["timeline_analysis"] = result
            elif i == 4:  # 完整性评估
                integrated["completeness_assessment"] = result
        
        return integrated
    
    async def _generate_risk_assessment(self, integrated_results: Dict[str, Any]) -> Dict[str, Any]:
        """生成风险评估"""
        risk_factors = []
        risk_score = 0.0
        
        # 分析各个维度的风险
        work_verification = integrated_results.get("work_verification", {})
        if work_verification.get("credibility_score", 0) < 70:
            risk_factors.append("工作经历可信度较低")
            risk_score += 0.3
        
        education_verification = integrated_results.get("education_verification", {})
        if education_verification.get("education_credibility", 0) < 70:
            risk_factors.append("教育背景存疑")
            risk_score += 0.2
        
        timeline_analysis = integrated_results.get("timeline_analysis", {})
        if timeline_analysis.get("gaps_identified"):
            risk_factors.append("时间线存在问题")
            risk_score += 0.2
        
        completeness_assessment = integrated_results.get("completeness_assessment", {})
        if completeness_assessment.get("completeness_score", 0) < 80:
            risk_factors.append("信息不够完整")
            risk_score += 0.1
        
        # 计算风险级别
        if risk_score >= 0.6:
            risk_level = "高风险"
        elif risk_score >= 0.3:
            risk_level = "中等风险"
        else:
            risk_level = "低风险"
        
        return {
            "risk_factors": risk_factors,
            "risk_score": min(risk_score, 1.0),
            "risk_level": risk_level,
            "overall_assessment": f"候选人背景核查结果显示{risk_level}"
        }
    
    async def _calculate_verification_score(self, integrated_results: Dict[str, Any]) -> Dict[str, float]:
        """计算验证分数"""
        scores = {
            "work_credibility": 0.0,
            "education_credibility": 0.0,
            "company_credibility": 0.0,
            "timeline_consistency": 0.0,
            "information_completeness": 0.0,
            "overall_verification": 0.0
        }
        
        # 从各个验证结果中提取分数
        work_verification = integrated_results.get("work_verification", {})
        scores["work_credibility"] = work_verification.get("credibility_score", 0)
        
        education_verification = integrated_results.get("education_verification", {})
        scores["education_credibility"] = education_verification.get("education_credibility", 0)
        
        company_verification = integrated_results.get("company_verification", {})
        scores["company_credibility"] = company_verification.get("overall_confidence", 0) * 100
        
        timeline_analysis = integrated_results.get("timeline_analysis", {})
        scores["timeline_consistency"] = timeline_analysis.get("consistency_score", 0)
        
        completeness_assessment = integrated_results.get("completeness_assessment", {})
        scores["information_completeness"] = completeness_assessment.get("completeness_score", 0)
        
        # 计算综合分数
        scores["overall_verification"] = sum(scores.values()) / 5
        
        return scores
    
    async def _generate_verification_recommendations(self, integrated_results: Dict[str, Any]) -> List[str]:
        """生成验证建议"""
        recommendations = []
        
        # 基于验证结果生成建议
        work_verification = integrated_results.get("work_verification", {})
        if work_verification.get("credibility_score", 0) < 80:
            recommendations.append("建议进行电话核实工作经历")
        
        education_verification = integrated_results.get("education_verification", {})
        if education_verification.get("education_credibility", 0) < 80:
            recommendations.append("建议要求提供学历证明文件")
        
        completeness_assessment = integrated_results.get("completeness_assessment", {})
        missing_elements = completeness_assessment.get("missing_elements", [])
        if missing_elements:
            recommendations.append(f"建议补充以下信息：{', '.join(missing_elements)}")
        
        if not recommendations:
            recommendations.append("背景信息验证良好，可以进入下一轮评估")
        
        return recommendations
    
    # 辅助方法
    async def _analyze_company_information(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析公司信息"""
        answer = rag_result.get("answer", "")
        
        return {
            "company_mentions": answer.count("公司"),
            "industry_mentions": self._count_industry_mentions(answer),
            "size_indicators": self._extract_company_size_indicators(answer)
        }
    
    def _count_industry_mentions(self, text: str) -> int:
        """统计行业提及"""
        industries = ["科技", "金融", "制造", "教育", "医疗", "咨询"]
        return sum(text.count(industry) for industry in industries)
    
    def _extract_company_size_indicators(self, text: str) -> List[str]:
        """提取公司规模指标"""
        size_indicators = ["大型", "中型", "小型", "初创", "上市", "跨国"]
        return [indicator for indicator in size_indicators if indicator in text]
    
    # 简化的其他方法实现
    async def _verify_company_existence_detailed(self, company_analysis: Dict[str, Any]) -> Dict[str, Any]:
        """详细验证公司存在性"""
        return {"status": "verified", "confidence": 0.85}
    
    async def _calculate_company_credibility(self, verification: Dict[str, Any]) -> float:
        """计算公司可信度"""
        return verification.get("confidence", 0.5) * 100
    
    async def _analyze_education_information(self, rag_result: Dict[str, Any]) -> Dict[str, Any]:
        """分析教育信息"""
        return {"schools_mentioned": 1, "degrees_mentioned": 1}
    
    async def _verify_educational_institutions(self, education_analysis: Dict[str, Any]) -> Dict[str, Any]:
        """验证教育机构"""
        return {"status": "verified", "confidence": 0.9}
    
    async def _calculate_education_credibility(self, verification: Dict[str, Any]) -> float:
        """计算教育可信度"""
        return verification.get("confidence", 0.8) * 100
    
    # 风险评估相关方法
    async def _analyze_employment_gaps(self, description: str) -> Dict[str, Any]:
        """分析就业空白"""
        return {"gaps_found": False, "total_gap_months": 0}
    
    async def _check_job_hopping_pattern(self, description: str) -> Dict[str, Any]:
        """检查跳槽模式"""
        return {"frequent_changes": False, "average_tenure": 24}
    
    async def _assess_information_consistency(self, description: str) -> Dict[str, Any]:
        """评估信息一致性"""
        return {"consistency_score": 0.85, "inconsistencies": []}
    
    async def _evaluate_reference_availability(self, description: str) -> Dict[str, Any]:
        """评估推荐人可用性"""
        return {"references_provided": True, "contact_info_complete": True}
    
    async def _integrate_risk_factors(self, risk_factors: List[Dict[str, Any]]) -> Dict[str, Any]:
        """整合风险因子"""
        return {
            "employment_risk": risk_factors[0] if len(risk_factors) > 0 else {},
            "job_stability_risk": risk_factors[1] if len(risk_factors) > 1 else {},
            "consistency_risk": risk_factors[2] if len(risk_factors) > 2 else {},
            "reference_risk": risk_factors[3] if len(risk_factors) > 3 else {}
        }
    
    async def _determine_risk_level(self, risk_assessment: Dict[str, Any]) -> str:
        """确定风险级别"""
        # 简化的风险级别判断
        return "低风险"
    
    async def _suggest_risk_mitigation(self, risk_assessment: Dict[str, Any]) -> List[str]:
        """建议风险缓解措施"""
        return ["建议进行电话核实", "建议要求提供推荐人联系方式"]